package com.ruoyi.web.controller.reward;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.points.domain.CommunityPointsLog;
import com.ruoyi.points.domain.CommunityUserPoints;
import com.ruoyi.points.service.ICommunityPointsLogService;
import com.ruoyi.points.service.ICommunityUserPointsService;
import com.ruoyi.reward.domain.CommunityOrder;
import com.ruoyi.reward.domain.CommunityRedemptionCode;
import com.ruoyi.reward.mapper.CommunityRewardMapper;
import com.ruoyi.reward.service.ICommunityOrderService;
import com.ruoyi.reward.service.ICommunityRedemptionCodeService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.reward.domain.CommunityReward;
import com.ruoyi.reward.service.ICommunityRewardService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 积分商品Controller
 * 
 * @author xianyu
 * @date 2025-04-04
 */
@RestController
@RequestMapping("/reward/reward")
public class CommunityRewardController extends BaseController
{
    @Autowired
    private ICommunityRewardService communityRewardService;
    @Autowired
    private ICommunityUserPointsService communityUserPointsService;
    @Autowired
    private ICommunityOrderService communityOrderService;
    @Autowired
    private ICommunityPointsLogService communityPointsLogService;
    @Autowired
    private ICommunityRedemptionCodeService communityRedemptionCodeService;
    /**
     * 查询积分商品列表
     */
//    @PreAuthorize("@ss.hasPermi('reward:reward:list')")
    @GetMapping("/list")
    public TableDataInfo list(CommunityReward communityReward)
    {
        startPage();
        List<CommunityReward> list = communityRewardService.selectCommunityRewardList(communityReward);
        return getDataTable(list);
    }

    /**
     * 导出积分商品列表
     */
    @PreAuthorize("@ss.hasPermi('reward:reward:export')")
    @Log(title = "积分商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CommunityReward communityReward)
    {
        List<CommunityReward> list = communityRewardService.selectCommunityRewardList(communityReward);
        ExcelUtil<CommunityReward> util = new ExcelUtil<CommunityReward>(CommunityReward.class);
        util.exportExcel(response, list, "积分商品数据");
    }

    /**
     * 获取积分商品详细信息
     */
//    @PreAuthorize("@ss.hasPermi('reward:reward:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(communityRewardService.selectCommunityRewardById(id));
    }

    /**
     * 新增积分商品
     */
    @PreAuthorize("@ss.hasPermi('reward:reward:add')")
    @Log(title = "积分商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CommunityReward communityReward)
    {
        return toAjax(communityRewardService.insertCommunityReward(communityReward));
    }
    // RewardController.java

//    /**
//     * 核验积分商品
//     */
////    @PreAuthorize("@ss.hasPermi('reward:reward:add')")
//    @Log(title = "核验积分商品", businessType = BusinessType.INSERT)
//    @PostMapping("/checkcode")
//    public AjaxResult checkcode(@RequestBody CommunityReward communityReward)
//    {
//        return toAjax(communityRewardService.updateCommunityReward(communityReward));
//    }
    /**
     * 修改积分商品
     */
//    @PreAuthorize("@ss.hasPermi('reward:reward:edit')")
    @Log(title = "积分商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CommunityReward communityReward)
    {
        return toAjax(communityRewardService.updateCommunityReward(communityReward));
    }

    /**
     * 修改积分商品状态
     */
    @PreAuthorize("@ss.hasPermi('reward:reward:edit')")
    @Log(title = "积分商品", businessType = BusinessType.UPDATE)
    @PutMapping("/status")
    public AjaxResult updateStatus(@RequestBody CommunityReward communityReward)
    {
        return toAjax(communityRewardService.updateCommunityReward(communityReward));
    }

    /**
     * 删除积分商品
     */
    @PreAuthorize("@ss.hasPermi('reward:reward:remove')")
    @Log(title = "积分商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(communityRewardService.deleteCommunityRewardByIds(ids));
    }

    /**
     * 积分兑换商品
     *
     */
//    @PreAuthorize("@ss.hasPermi('reward:reward:edit')")
    @Log(title = "积分商品", businessType = BusinessType.UPDATE)
    @PutMapping("/exchange/{rewardId}")
    public AjaxResult exchange(@PathVariable Integer rewardId)
    {
//        System.out.println("rewardId: " + rewardId);
        // 1. 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = loginUser.getUserId();
        //数据类型转化
        Long rewardIdLong = Long.valueOf(rewardId);
        System.out.println(1);
        // 2. 校验商品信息
        CommunityReward reward = communityRewardService.selectCommunityRewardById(rewardIdLong);
        if (reward == null) {
            return AjaxResult.error("商品不存在");
        }
        if (reward.getStatus() != 1L) {
            return AjaxResult.error("商品已下架");
        }
        System.out.println(2);

        // 3. 校验用户积分
        CommunityUserPoints userPoints = communityUserPointsService.selectCommunityUserPointsById(userId);
        long totalCost = reward.getPointsCost() * 1;
        if (userPoints.getPoints() < totalCost) {
            return AjaxResult.error("积分不足，当前积分：" + userPoints.getPoints());
        }
        System.out.println("开始检验库存");
        // 4. 校验库存（带乐观锁）
        int affectedRows = communityRewardService.reduceStock(rewardIdLong, 1);
        if (affectedRows == 0) {
            return AjaxResult.error("库存不足");
        }
        System.out.println(4);

        // 5. 扣减积分（带版本号乐观锁）
        userPoints.setPoints(userPoints.getPoints() - totalCost);
//        System.out.println("userPoints: " + userPoints);
        int updateResult = communityUserPointsService.updateUserPointsWithVersion(userPoints);
        if (updateResult == 0) {
            throw new RuntimeException("积分扣减失败，请重试");
        }
        System.out.println(5);

        // 6. 创建订单
        CommunityOrder order = new CommunityOrder();
        order.setUserId(userId);
        order.setRewardId(rewardIdLong);
        order.setPointsCost(totalCost);
        order.setStatus("pending");
        communityOrderService.insertCommunityOrder(order);
        System.out.println(6);

        // 7. 记录积分流水
        CommunityPointsLog log = new CommunityPointsLog();
        log.setUserId(userId);
        log.setPoints(-totalCost);
        log.setSourceType("商品兑换");
        log.setSourceId(order.getId());
        communityPointsLogService.insertCommunityPointsLog(log);

//        //8.生成随机兑换码并保存
        String code = userId+"*"+RandomStringUtils.randomAlphanumeric(10);
        CommunityRedemptionCode communityRedemptionCode = new CommunityRedemptionCode();
        communityRedemptionCode.setCode(code);
        communityRedemptionCode.setOrderId(order.getId());
        communityRedemptionCode.setIsUsed(0L);
//        System.out.println(DateUtils.getNowDate());
        Calendar calendar = Calendar.getInstance();
//        Date now = calendar.getTime();
        // 增加一天
        calendar.add(Calendar.DAY_OF_MONTH, 30);
        Date deadlineTime = calendar.getTime();
        communityRedemptionCode.setExpireTime(deadlineTime);
        communityRedemptionCodeService.insertCommunityRedemptionCode(communityRedemptionCode);
        return AjaxResult.success("兑换成功");
    }
}
